# -*- coding: utf-8 -*- 
"""
========================================================================================================================
@project : my-sanic
@file: myMiddleware
@Author: mengying
@email: 652044581@qq.com
@date: 2023/3/3 11:34
@desc: 系统的中间件
========================================================================================================================
"""
from sanic import Sanic
from config import config
from sanic.exceptions import NotFound
from utils.myResFormat import ResultCode, ResultJson
from sanic.response import json as JsonResponse
from middleware.myAuthorization import Authorization
from middleware.myProcessLog import ProcessLog

app = Sanic.get_app(config.PROJECT_NAME)


@app.middleware('request')
async def process_request(request):
    # 记录请求日志
    ProcessLog(request=request, response=None).action()

    # 检查白名单
    if not Authorization.white_list_check(request):

        # 在header里面增加用户信息
        await Authorization.get_user_info(request)

        user_info = request.headers.get("user_info", {})

        if not user_info:
            return JsonResponse(ResultJson(ResultCode.TOKEN_ERROR).result)


@app.middleware('response')
async def process_response(request, response):
    ProcessLog(request=request, response=response).action()


@app.exception(Exception)
async def process_error(request, exception):
    # 路径错误处理
    if getattr(exception, "status_code", None) == 404:
        raise NotFound("路由未找到")

    return JsonResponse(ResultJson(ResultCode.SERVER_ERROR, description=str(exception)).result)